package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private IVoucherService voucherService;
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    // 加载 lua 脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    // 阻塞队列
//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    // 线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct // 在当前类初始化完毕之后就执行
    private void init() {
        // 阻塞队列
//        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
        // 消息队列
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandlerStream());
    }

    // 线程任务
//    private class VoucherOrderHandler implements Runnable {
//        @Override
//        public void run() {
//            while (true) { // 不会有负担
//                try {
//                    // 1. 获取队列中的订单信息
//                    VoucherOrder take = orderTasks.take();// 获取队列中的头部
//                    // 2. 创建订单
//                    handleVoucherOrder(take);
//                } catch (InterruptedException e) {
//                    log.error("处理订单异常", e);
//                }
//            }
//        }
//    }

    private class VoucherOrderHandlerStream implements Runnable {
        String QueueName = "stream.orders";

        @Override
        public void run() {
            while (true) {
                try {
                    // 1. 获取消息队列中的订单消息
                    // XREADGROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> readList = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(QueueName, ReadOffset.lastConsumed())
                    );
                    // 2. 判断消息是否获取成功
                    // 2.1 获取失败，没有消息，下一次循环
                    if (readList == null || readList.isEmpty()) {
                        continue;
                    }
                    // 2.2.1 解析消息
                    MapRecord<String, Object, Object> record = readList.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    // 2.2.2 获取成功，处理信息，下单
                    handleVoucherOrder(voucherOrder);
                    // 3. ACK 确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(QueueName, "g1", record.getId());
                } catch (Exception e) {
                    // 处理异常消息，消息进入 pending-list
                    log.error("处理订单异常,进入 pending-list 处理环节", e);
                    try {
                        handlePendingList();
                    } catch (InterruptedException ex) {
                        log.error(" 处理pending-list 的代码异常", ex);
                    }
                }
            }
        }

        private void handlePendingList() throws InterruptedException {
            while (true) {
                try {
                    // 1. 获取 pending-list 中的订单消息
                    // XREADGROUP g1 c1 COUNT 1 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> readList = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(QueueName, ReadOffset.from("0"))
                    );
                    // 2. 判断消息是否获取成功
                    // 2.1 获取失败，pending-list 没有消息，结束循环
                    if (readList == null || readList.isEmpty()) {
                        break;
                    }
                    // 2.2.1 解析消息
                    MapRecord<String, Object, Object> record = readList.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    // 2.2.2 获取成功，处理信息，下单
                    handleVoucherOrder(voucherOrder);
                    // 3. ACK 确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(QueueName, "g1", record.getId());
                } catch (Exception e) {
                    // 处理pending-list 后异常消息，不用递归，因为本身就是 while
                    log.error("处理 pending-list 订单异常", e);
                    // 休眠，不让处理的那么块
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }

    private IVoucherOrderService proxy;

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        // 1. 创建锁对象
        RLock lock = redissonClient.getLock("voucher:order:" + voucherOrder.getUserId());
        // 2. 获取锁
        boolean isLock = lock.tryLock();
        // 3. 判断是否获取到锁
        if (!isLock) {
            // 失败
            log.error("获取锁失败");
            return;
        }
        try {
            // 4. 获取代理对象(事务)
            // 因为这是一个新的线程，所以需要在主线程中获取代理对象
            proxy.createVoucherOrder(voucherOrder);
        } catch (IllegalStateException e) {
            throw new RuntimeException(e);
        } finally {
            // 要放在 try-catch-finally 内，最后释放锁
            lock.unlock();
        }
    }


    @Override
    public Result seckillVoucherLuaStream(Long voucherId) {
        // 0. 获取用户 id
        Long userId = UserHolder.getUser().getId();
        // 0. 获取订单 id
        long orderId = redisIdWorker.nextId("order");
        // 1. 执行 lua 脚本，发送了消息到消息队列
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),  // key
                voucherId.toString(), userId.toString(), String.valueOf(orderId)  // orderId,userId,voucherId
        );
        // 2.1 判断脚本结果是否为0（1库存无，2已购买）
        if (result.intValue() == 1) {
            return Result.fail("没有库存啦!");
        } else if (result.intValue() == 2) {
            return Result.fail("您已购买过啦!");
        }
        // 2.2 异步下单
        // 2.2 获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        // 3. 返回订单 ID
        return Result.ok(orderId);
    }

    @Override
    public Result seckillVoucherLua(Long voucherId) {
        // 0. 获取用户
        Long userId = UserHolder.getUser().getId();
        // 1. 执行 lua 脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),  // key
                voucherId.toString(), userId.toString() // voucherId, userId
        );
        // 2.1 判断脚本结果是否为0（1库存无，2已购买）
        if (result.intValue() == 1) {
            return Result.fail("没有库存啦!");
        } else if (result.intValue() == 2) {
            return Result.fail("您已购买过啦!");
        }
        // 2.2 有资格，保存到阻塞队列
        long orderId = redisIdWorker.nextId("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId); // 订单ID
        voucherOrder.setUserId(userId);  // 用户ID
        voucherOrder.setVoucherId(voucherId);  // 代金券ID
//        orderTasks.add(voucherOrder);

        // 2.3 异步下单
        // 2.3.1 获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        // 3. 返回订单 ID
        return Result.ok(orderId);
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        // 查询优惠券
        Voucher voucher = voucherService.getById(voucherId);
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);

        // 判断秒杀开始结束时间
        LocalDateTime beginTime = seckillVoucher.getBeginTime();
        LocalDateTime endTime = seckillVoucher.getEndTime();
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(beginTime)) {
            return Result.fail("秒杀尚未开始");
        }
        if (now.isAfter(endTime)) {
            return Result.fail("秒杀已经结束");
        }

        // 判断库存
        int stock = seckillVoucher.getStock();
        if (stock < 1) {
            return Result.fail("库存不足");
        }

        Long orderId = redisIdWorker.nextId("order");
        Long userId = UserHolder.getUser().getId();

        // TODO 自定义分布式锁，创建锁对象
        // 锁定范围较小，并发效率高
//        SimpleRedisLock lock = new SimpleRedisLock("voucher:order:" + userId, stringRedisTemplate);
//        boolean isLock = lock.tryLock(1200);// 时间与业务有关

        // TODO 使用 Redisson 创建锁对象
        RLock lock = redissonClient.getLock("voucher:order:" + userId);
        boolean isLock = lock.tryLock(); // 无参：waitTime = -1，leaseTime = 30

        // 判断是否获取到锁
        if (!isLock) {
            // 获取锁失败，报错 / 重试
            return Result.fail("您已下单，不许重复下单");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            // 创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
            voucherOrder.setId(voucherOrder.getId()); // 订单ID
            voucherOrder.setUserId(voucherOrder.getUserId());  // 用户ID
            voucherOrder.setVoucherId(voucherOrder.getVoucherId());  // 代金券ID
            return proxy.createVoucherOrder(voucherOrder);
        } catch (IllegalStateException e) {
            throw new RuntimeException(e);
        } finally {
            // 要放在 try-catch-finally 内，最后释放锁
            lock.unlock();
        }

//         先获取锁，再进入函数完成下单操作，等函数执行完，说明订单一定写入数据库了，因为事务提交了
//        synchronized (String.valueOf(userId).intern()) {  // id 值一样的作为一把锁
//             获取事务有关的代理对象
//             调用方法 createVoucherOrder
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId, orderId, userId);
//        } // 释放锁的这一刻，确保数据库中已经有我下的订单了，那么其他线程来就不会重复下单了
    }

    @Transactional
    public Result createVoucherOrder(VoucherOrder voucherOrder) {
        // 一人一单
        int count = query()
                .eq("user_id", voucherOrder.getUserId())
                .eq("voucher_id", voucherOrder.getVoucherId())
                .count();
        if (count > 0) {
            return Result.fail("该用户已下单此券");
        }

        // 扣减库存
        boolean success = seckillVoucherService
                .update()
                .setSql("stock = stock -1")
                .eq("voucher_id", voucherOrder.getVoucherId())
//                .eq("stock", seckillVoucher.getStock()) // 乐观锁体现
                .gt("stock", 0) // 乐观锁改进， >0
                .update();
        if (!success) {
            return Result.fail("库存不足！");
        }
        save(voucherOrder);
        log.info("订单已经保存，业务完成");
        // 返回订单id
        return Result.ok(voucherOrder.getId());
    }
}
